package com.mugui.sql.datasource;

import com.mugui.sql.DBConf;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import lombok.Getter;

@Getter
public class HikariCPDataSource implements DataSource {

	/**
	 * 加载默认的数据源
	 */
	public synchronized final HikariDataSource getDataSource() {
		return init(DBConf.getDefaultDBConf());
	}

	/**
	 * 通过数据库配置类加载一个数据源
	 * 
	 * @param dbConf
	 */
	public synchronized final HikariDataSource getDataSource(DBConf dbConf) {
		return init(dbConf);
	}

	/**
	 * 通过url加载一个数据源
	 * 
	 * @param url
	 */
	public synchronized final HikariDataSource getDataSource(String url) {
		return init(DBConf.getDBConf(url));
	}

	static HikariDataSource init(DBConf dbConf) {
		try {
			HikariConfig config = new HikariConfig();
			config.setJdbcUrl(dbConf.getUrl());
			config.setUsername(dbConf.getUser());
			config.setPassword(dbConf.getPwd());
			config.setDriverClassName(dbConf.getDrive());
			config.setConnectionTimeout(30000);
			config.setIdleTimeout(540000);
			config.setMaxLifetime(1800000);
//			config.setConnectionTestQuery("select 1");
			config.setConnectionInitSql("select 1");
			config.setValidationTimeout(5000);
			config.setAutoCommit(true);
			config.setMaximumPoolSize(dbConf.getMaxPoolSize());
			config.setMinimumIdle(dbConf.getMinimumldle());
			
//			config.addDataSourceProperty("serverTimezone","UTC");
			config.addDataSourceProperty("characterEncoding","utf-8");
//			config.addDataSourceProperty("autoReconnect","true");
			config.addDataSourceProperty("failOverReadOnly","false");
			HikariDataSource hikariDataSource = new HikariDataSource(config);
			dbConf.setDataSource(hikariDataSource);
			return hikariDataSource;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("无法加载：" + dbConf);
		}
	}
}
